package com.wanqing.community.util;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

public class JsonUtil {

	public static String getRequestJson(HttpServletRequest request) {
		String requeststr="";
		StringBuffer jb = new StringBuffer();    
		String line = null;    
		try {    
			BufferedReader reader = request.getReader();    
			while ((line = reader.readLine()) != null){
				jb.append(line);    
			}
       } catch (Exception e) {} 
       requeststr = jb.toString();
       if(requeststr.equals("")){
    	   requeststr = request.getParameter("jsonParam")==null?"":request.getParameter("jsonParam");
       }
       return requeststr;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> getDTOList(String jsonString, Class<T> clazz){
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		List<T> list = new ArrayList<T>();
		for(Iterator iter = array.iterator(); iter.hasNext();){
			JSONObject jsonObject = (JSONObject)iter.next();
			list.add((T) JSONObject.toBean(jsonObject, clazz));
		}
		return list;
	}
	private static void setDataFormat2JAVA(){
		//设定日期转换格式
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"}));
	}
}
